<template>
  <div class="member-info-container">
    <div class="form-wrapper">
      <div class="page-title">
        <h2>完善档案信息</h2>
      </div>

      <el-form
          ref="formRef"
          :model="memberForm"
          :rules="formRules"
          label-width="100px"
          class="member-form"
          label-position="right"
      >
        <div class="section-title">居民信息</div>

        <el-row :gutter="40" class="form-row">
          <el-col :span="8">
            <el-form-item label="居民编号">
              <el-input
                  v-model="residentId"
                  class="form-input"
                  readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="姓名" prop="name" required>
              <el-input
                  v-model="memberForm.name"
                  class="form-input"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="居民头像">
              <div class="avatar-section">
                <div class="avatar-placeholder">
                  <el-icon class="avatar-icon"><User /></el-icon>
                </div>
                <el-button type="text" class="upload-link">点击上传</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="40" class="form-row">
          <el-col :span="8">
            <el-form-item label="身份证号" prop="idCard" required>
              <el-input
                  v-model="memberForm.idCard"
                  class="form-input"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号码" prop="phone" required>
              <el-input
                  v-model="memberForm.phone"
                  class="form-input"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="居民标签">
              <el-select
                  v-model="memberForm.tag"
                  placeholder="请选择"
                  class="form-select"
                  multiple
              >
                <el-option v-for="t in tagOptions" :key="t.name" :label="t.name" :value="t.name"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="40" class="form-row">
          <el-col :span="8">
            <el-form-item label="行政区划">
              <el-input
                  v-model="memberForm.district"
                  placeholder="请输入"
                  class="form-input"
              />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="家庭地址">
              <el-input
                  v-model="memberForm.address"
                  placeholder="请输入"
                  class="form-input"
              />
            </el-form-item>
          </el-col>
        </el-row>


        <el-row :gutter="40" class="form-row">
          <el-col :span="8">
            <el-form-item label="性别">
              <el-select
                  v-model="memberForm.gender"
                  placeholder="请选择"
                  class="form-select"
              >
                <el-option label="男" :value="1" />
                <el-option label="女" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出生年月">
              <el-date-picker
                  v-model="memberForm.birthdate"
                  type="date"
                  placeholder="请选择日期"
                  class="form-input"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="籍贯">
              <el-input
                  v-model="memberForm.originPlace"
                  placeholder="请输入"
                  class="form-input"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="40" class="form-row">
          <el-col :span="8">
            <el-form-item label="民族">
              <el-select
                  v-model="memberForm.nation"
                  placeholder="请选择"
                  class="form-select"
              >
                <el-option label="汉族" value="汉族" />
                <el-option label="回族" value="回族" />
                <el-option label="苗族" value="苗族" />
                <el-option label="朝鲜族" value="朝鲜族" />
                <el-option label="维吾尔族" value="维吾尔族" />

              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="文化程度">
              <el-select
                  v-model="memberForm.education"
                  placeholder="请选择"
                  class="form-select"
              >
                <el-option label="小学" value="小学" />
                <el-option label="初中" value="初中" />
                <el-option label="高中" value="高中" />
                <el-option label="大学" value="大学" />
                <el-option label="本科" value="本科" />
                <el-option label="博士" value="博士" />
                <el-option label="硕士" value="硕士" />
                <el-option label="研究生" value="研究生" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="婚姻状况">
              <el-select
                  v-model="memberForm.maritalStatus"
                  placeholder="请选择"
                  class="form-select"
              >
                <el-option label="未婚" value="未婚" />
                <el-option label="已婚" value="已婚" />
                <el-option label="离异" value="离异" />
                <el-option label="丧偶" value="丧偶" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第七行：职业、工作单位 -->
        <el-row :gutter="40" class="form-row">
          <el-col :span="8">
            <el-form-item label="年龄">
              <el-input
                  v-model="memberForm.age"
                  placeholder="请输入"
                  class="form-input"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="职业">
              <el-input
                  v-model="memberForm.occupation"
                  placeholder="请输入"
                  class="form-input"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="费用类型">
              <el-select
                  v-model="memberForm.costType"
                  placeholder="请选择"
                  class="form-select"
              >
                <el-option label="自费" value="自费" />
                <el-option label="商业保险" value="商业保险" />
                <el-option label="社会医疗保险" value="社会医疗保险" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row :gutter="40" class="form-row">
          <el-col :span="8">
            <el-form-item label="登录密码" required>
              <el-input
                  v-model="memberForm.password"
                  type="password"
                  placeholder="请输入大于6位小于12位数字字母组合"
                  class="form-input"
                  show-password
              />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="定点医疗单位">
              <el-input
                  v-model="memberForm.medicalUnit"
                  placeholder="请输入"
                  class="form-input"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <div class="section-title">健康信息</div>

        <!-- 健康信息第一行：身高、体重、血型 -->
        <el-row :gutter="40" class="form-row">
          <el-col :span="6">
            <el-form-item label="身高">
              <div class="input-with-unit">
                <el-input
                    v-model="memberForm.health.height"
                    placeholder="请输入"
                    class="form-input"
                />
                <span class="unit">cm</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="体重">
              <div class="input-with-unit">
                <el-input
                    v-model="memberForm.health.weight"
                    placeholder="请输入"
                    class="form-input"
                />
                <span class="unit">kg</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="血型">
              <el-select
                  v-model="memberForm.health.bloodType"
                  placeholder="请选择"
                  class="form-select"
              >
                <el-option label="A型" value="A" />
                <el-option label="B型" value="B" />
                <el-option label="AB型" value="AB" />
                <el-option label="O型" value="O" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="RH阴性">
              <el-select
                  v-model="memberForm.health.rhNegative"
                  placeholder="请选择"
                  class="form-select"
              >
                <el-option label="是" :value="1" />
                <el-option label="否" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>



        <el-row :gutter="20" class="form-row">
          <el-col :span="6">
            <el-form-item label="过敏史">
              <el-radio-group v-model="historyRadio.allergyHistory">
                <el-radio label="无">无</el-radio>
                <el-radio label="有">有</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="10" v-if="historyRadio.allergyHistory === '有'">
            <el-form-item label="">
              <el-input
                  v-model="historyInput.allergyHistory"
                  placeholder="请输入过敏史详情"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 既往史 -->
        <el-row :gutter="20" class="form-row">
          <el-col :span="6">
            <el-form-item label="既往史">
              <el-radio-group v-model="historyRadio.medicalHistory">
                <el-radio label="无">无</el-radio>
                <el-radio label="有">有</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="10" v-if="historyRadio.medicalHistory === '有'">
            <el-form-item label="">
              <el-input
                  v-model="historyInput.medicalHistory"
                  placeholder="请输入既往史详情"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 就诊史 -->
        <el-row :gutter="20" class="form-row">
          <el-col :span="6">
            <el-form-item label="就诊史">
              <el-radio-group v-model="historyRadio.visitHistory">
                <el-radio label="无">无</el-radio>
                <el-radio label="有">有</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="10" v-if="historyRadio.visitHistory === '有'">
            <el-form-item label="">
              <el-input
                  v-model="historyInput.visitHistory"
                  placeholder="请输入就诊史详情"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 家族病史 -->
        <el-row :gutter="20" class="form-row">
          <el-col :span="6">
            <el-form-item label="家族病史">
              <el-radio-group v-model="historyRadio.familyHistory">
                <el-radio label="无">无</el-radio>
                <el-radio label="有">有</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="10" v-if="historyRadio.familyHistory === '有'">
            <el-form-item label="">
              <el-input
                  v-model="historyInput.familyHistory"
                  placeholder="请输入家族病史详情"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row class="form-actions">
          <el-col :span="24">
            <div class="button-group">
              <el-button class="cancel-btn" @click="handleCancel">返回</el-button>
              <el-button type="primary" class="save-btn" @click="handleSubmit">保存</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, watch} from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { User } from '@element-plus/icons-vue'
import axios from "axios";
import {ElMessage} from "element-plus";

const router = useRouter()
const route = useRoute()
const formRef = ref()

// 表单数据
const memberForm = ref({
  health: {
    height: null,
    weight: null,
    bloodType: '',
    rhNegative: null,
    allergyHistory: '',
    medicalHistory: '',
    visitHistory: '',
    familyHistory: ''
  }
})


const historyFields = ['allergyHistory', 'medicalHistory', 'visitHistory', 'familyHistory']

// 状态管理：记录每一项是否为“有”
const historyRadio = reactive({
  allergyHistory: '无',
  medicalHistory: '无',
  visitHistory: '无',
  familyHistory: '无'
})

// 输入框内容临时缓存
const historyInput = reactive({
  allergyHistory: '',
  medicalHistory: '',
  visitHistory: '',
  familyHistory: ''
})

watch(historyRadio, () => {
  historyFields.forEach(field => {
    if (historyRadio[field] === '无') {
      historyInput[field] = ''
      memberForm.value.health[field] = '无'
    } else {
      memberForm.value.health[field] = historyInput[field]
    }
  })
}, { deep: true })

watch(historyInput, () => {
  historyFields.forEach(field => {
    if (historyRadio[field] === '有') {
      memberForm.value.health[field] = historyInput[field]
    }
  })
}, { deep: true })

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  idCard: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
  password: [{ required: true, message: '请输入登录密码', trigger: 'blur' }]
}

// 提交表单
const handleSubmit = async () => {
  // 确保在提交前同步所有健康信息
  historyFields.forEach(field => {
    if (historyRadio[field] === '有') {
      memberForm.value.health[field] = historyInput[field]
    } else {
      memberForm.value.health[field] = '无'
    }
  })

  const payload = { ...memberForm.value, id: residentId.value }

  console.log('提交的完整数据:', payload)
  console.log('健康信息数据:', payload.health)

  try {
  if (isEditMode.value) {
      const response = await axios.put('/resident/updateResident', payload)
      console.log('更新响应:', response.data)
    ElMessage.success('居民信息更新成功')
  } else {
      const response = await axios.post('/resident/addResident', payload)
      console.log('添加响应:', response.data)
    ElMessage.success('居民添加成功')
  }

    router.push('/main/ResidentManagement')
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message))
  }
}

const tagOptions = ref([])

const id = route.query?.id

const getAllTag = () => {
  axios.get("/tag/getAllTag").then(resp => {
    tagOptions.value = resp.data;
  })
}

const getResidentId = async () => {
  const res = await axios.get('/resident/getResidentId')
  residentId.value = res.data
}

const loadResidentDetail = async (id) => {
  try {
  const res = await axios.get(`/resident/getResidentById?id=${id}`)
  const data = res.data
    console.log('后端返回的数据:', data)

  residentId.value = data.id
  memberForm.value = data

    // 确保 health 对象存在并正确处理
    if (!data.health) {
      memberForm.value.health = {
        height: null,
        weight: null,
        bloodType: '',
        rhNegative: null,
        allergyHistory: '',
        medicalHistory: '',
        visitHistory: '',
        familyHistory: ''
      }
    } else {
  memberForm.value.health = data.health

      // 根据后端数据设置前端状态
      historyFields.forEach(field => {
        const value = data.health[field]
        if (value && value !== '无' && value !== '' && value !== null) {
          historyRadio[field] = '有'
          historyInput[field] = value
        } else {
          historyRadio[field] = '无'
          historyInput[field] = ''
        }
      })
    }

    console.log('处理后的表单数据:', memberForm.value)
  } catch (error) {
    console.error('加载居民详情失败:', error)
    ElMessage.error('加载居民详情失败')
  }
}

const isEditMode = ref(false)
const residentId = ref(null)

onMounted(() => {
  getAllTag()
  if (id) {
    isEditMode.value = true
    residentId.value = id
    loadResidentDetail(id)
    console.log(id)
  } else {
    isEditMode.value = false
    getResidentId()
  }
})

// 取消/返回
const handleCancel = () => {
  router.back()
}
</script>

<style scoped>
.member-info-container {
  width: 1400px;
  margin: 0 auto;
  padding: 0;
  background-color: #ffffff;
  min-height: 100vh;
}

.form-wrapper {
  background-color: #ffffff;
  padding: 40px 60px;
}

.page-title {
  text-align: left;
  margin-bottom: 40px;
  padding-left: 20px;
}

.page-title h2 {
  color: #4b4b4b;
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  position: relative;
}

.page-title h2::before {
  content: '';
  position: absolute;
  left: -20px;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background-color: #409eff;
  border-radius: 2px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #000000;
  margin: 40px 0 30px 0;
  padding: 0;
  border: none;
}

.member-form {
  max-width: none;
}

.form-row {
  margin-bottom: 25px;
}

.form-input,
.form-select {
  width: 100%;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.avatar-placeholder {
  width: 50px;
  height: 50px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
}

.avatar-icon {
  font-size: 24px;
  color: #c0c4cc;
}

.upload-link {
  color: #409eff;
  padding: 0;
  font-size: 14px;
}

.input-with-unit {
  position: relative;
}

.unit {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  font-size: 14px;
  pointer-events: none;
}

.fee-type-item {
  margin-bottom: 0;
}

.checkbox-group {
  display: flex;
  gap: 40px;
  flex-wrap: wrap;
}

.form-actions {
  margin-top: 50px;
  padding-top: 30px;
}

.button-group {
  text-align: center;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.cancel-btn {
  padding: 10px 30px;
  font-size: 16px;
  border: 1px solid #dcdfe6;
  color: #606266;
  background-color: #ffffff;
}

.save-btn {
  padding: 10px 30px;
  font-size: 16px;
  background-color: #409eff;
  border-color: #409eff;
}

/* Element Plus 样式覆盖 */
:deep(.el-form-item__label) {
  color: #999999;
  font-weight: 400;
  font-size: 14px;
  text-align: right;
  padding-right: 12px;
}

:deep(.el-form-item--required .el-form-item__label::before) {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

:deep(.el-input__wrapper) {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: none;
}

:deep(.el-input__wrapper:hover) {
  border-color: #c0c4cc;
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
}

:deep(.el-select .el-input__wrapper) {
  border: 1px solid #dcdfe6;
}

:deep(.el-date-editor) {
  width: 100%;
}

:deep(.el-date-editor .el-input__wrapper) {
  border: 1px solid #dcdfe6;
}

:deep(.el-checkbox) {
  margin-right: 0;
  color: #000000;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-radio) {
  margin-right: 20px;
  color: #000000;
}

:deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-radio__inner::after) {
  background-color: #fff;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}
</style>
